package com.myway.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.myway.dto.Result.Flights;
import com.myway.dto.common.JsonData;
import com.myway.dto.domain.GlobalResult;
import com.myway.dto.domain.TotalFlyPrice;
import com.myway.dto.ibe_param.TaxPrice;
import com.myway.dto.ibe_param.TicketPrice;
import com.myway.dto.payment.oceanpayment.OceanpaymentParams;
import com.myway.dto.vo.FlyOrderVo;
import com.myway.dto.vo.FlyPassengeVo;
import com.myway.dto.vo.FlySegmentVo;
import com.myway.service.PaymentService;
import com.myway.utils.Encrypt;
import com.myway.utils.OrderNumberGenerator;
import com.myway.utils.UserUtils;
import com.myway.service.AVService;
import com.myway.service.CountPriceService;
import com.myway.service.TicketService;
import com.myway.service.payment.Oceanpayment.OceanpaymentServcie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by qianmi-05 on 2018/8/6.
 */

@Controller
@RequestMapping("/en/flyayment")
public class FlyaymentController {

    @Autowired
    private CountPriceService countPriceService;
    @Autowired
    private AVService avService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private OceanpaymentServcie oceanpaymentServcie;
    @Autowired
    private TicketService ticketService;

    @RequestMapping("/toPay")
    @ResponseBody
    public ModelAndView toPay(@RequestParam(value="orderId",required = false)String orderId,
                              @RequestParam(value = "payType",required = false)String payType){
        Map map=new HashMap<String,Object>();
        OceanpaymentParams oceanpaymentParams = oceanpaymentServcie.OceanpaymentToPay(orderId, "");
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("oceanpaymentParams",oceanpaymentParams);
        modelAndView.setViewName("/en/paymentFrom");
        return modelAndView;

    }
    @RequestMapping("/oceanpaymentCallBack")
    @ResponseBody
    public ModelAndView oceanpaymentCallBack(HttpServletRequest request){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("/en/payResult");

        Map<String, String[]> $_REQUEST = request.getParameterMap();
        //返回商户号
        String $account = $_REQUEST.get("account")[0];
        //返回终端号
        String  $terminal = $_REQUEST.get("terminal")[0];
        //返回Oceanpayment 的支付唯一号
        String  $payment_id=$_REQUEST.get("payment_id")[0];
        //返回网站订单号
        String  $order_number=$_REQUEST.get("order_number")[0];
        //返回交易币种
        String  $order_currency=$_REQUEST.get("order_currency")[0];
        //返回支付金额
        String $order_amount =$_REQUEST.get("order_amount")[0];
        //返回支付状态
        String $payment_status   = $_REQUEST.get("payment_status")[0];
        //返回支付详情
        String $payment_details   = $_REQUEST.get("payment_details")[0];
        //返回交易安全签名
        String $back_signValue   = $_REQUEST.get("signValue")[0];
        //返回备注
        String $order_notes   = $_REQUEST.get("order_notes")[0];
        //返回支付方式
        String $methods   = $_REQUEST.get("methods")[0];
        //消费者所在国
        String $payment_country   = $_REQUEST.get("payment_country")[0];
        //未通过的风控规则
        String $payment_risk   = $_REQUEST.get("payment_risk")[0];
        //获取本地的code值
        String $secureCode      = "12345678";
        //返回支付信用卡卡号
        String $card_number      =  $_REQUEST.get("card_number")[0];
        //返回交易类型
        String $payment_authType      =  $_REQUEST.get("payment_authType")[0];

        String  $local_signValue="";
        String  str=$account+$terminal+$order_number+$order_currency+$order_amount+$order_notes+$card_number+$payment_id+$payment_authType+$payment_status+$payment_details+$payment_risk+"12345678";
        $local_signValue= Encrypt.String2SHA256(str);

        oceanpaymentServcie.addPaymentInfo($payment_id, $order_number, $order_currency, $order_amount, $methods, $card_number, $order_notes, $payment_status);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("account",$account);
        map.put("terminal",$terminal);
        map.put("$payment_id",$payment_id);
        map.put("$order_number",$order_number);
        map.put("$payment_status",$payment_status);
        map.put("$payment_details",$payment_details);
        map.put("$back_signValue",$back_signValue);
        map.put("$order_notes",$order_notes);
        map.put("$methods",$methods);
        map.put("$payment_country",$payment_country);
        map.put("$payment_risk",$payment_risk);
        map.put("$card_number",$card_number);
        map.put("$payment_authType",$payment_authType);
        map.put("$order_amount",$order_amount);
        map.put("$order_currency",$order_currency);
        modelAndView.addObject("map",map);
        if ($local_signValue.toLowerCase().equals($back_signValue.toLowerCase())) {
            if ($payment_status .equals("1")) {
                JsonData jsonData = ticketService.handleTicket($order_number);
                System.out.println("jsonData==========="+jsonData);
                //支付成功
                //展示付款成功页面给消费者看
            }else if($payment_status.equals("-1")){
                //支付待处理
                if ($payment_authType.equals("1")) {
                    //信用卡预授权，启用预授权才会有
                    //展示付款成功页面给消费者看
                    //订单需要人工审核
                }else{
                    //其他异常情况
                    //支付失败
                }
            }else if($payment_status.equals("0")){
                //支付失败
                //展示付款失败页面给消费者看
            }
        }else{
            //校验失败
            //展示付款失败页面给消费者看
        }

        return modelAndView;
    }

    @RequestMapping(value = "/flyOrder",method = RequestMethod.POST)
   // @ResponseBody
    public ModelAndView flyOrder(HttpServletRequest request,@RequestParam("orderVal")String orderVal,@RequestParam("tokenVal")String tokenVal)throws Exception{

        boolean b = isRepeatSubmit(request);// 判断用户是否是重复提交
        if (b == true) {
            System.out.println("请不要重复提交");
        }


        request.getSession().removeAttribute("token");// 移除session中的token
        List<FlyPassengeVo> adultPassagesList = (List<FlyPassengeVo>) request.getSession().getAttribute("adultPassages");

        orderVal=orderVal.replaceAll("orderVal=","");
        FlyOrderVo flyOrderVo = JSONObject.parseObject(orderVal,FlyOrderVo.class);


        ModelAndView modelAndView = new ModelAndView();
        List<TicketPrice> ticketPrice= (List<TicketPrice>) request.getSession().getAttribute("priceSession");
        ArrayList<Flights> flights = (ArrayList<Flights>)request.getSession().getAttribute("flghts");
        modelAndView.addObject("passengers", adultPassagesList/*flyOrderVo.getPassenges()*/);//旅客
        Map map=countPriceService.countCabinTypePrice(ticketPrice);
        modelAndView.addObject("cabinTypePrice",map.get("cabinTypePrice"));//税费
        modelAndView.addObject("totalFlyPrice",map.get("totalFlyPrice"));//机票价
        TotalFlyPrice totalFlyPrice= (TotalFlyPrice) map.get("totalFlyPrice");
        int adtCount=0,chdCount=0,infantCound=0;
        for(FlyPassengeVo pass:flyOrderVo.getPassenges()){
            if(pass.getPassageType().equals("1")){
                adtCount++;
            }else if(pass.getPassageType().equals("2")){
                chdCount++;
            }else if(pass.getPassageType().equals("3")){
                infantCound++;
            }
            if(pass.getAccompanyingPassengerList()!=null&&pass.getAccompanyingPassengerList().size()>0){
                for(FlyPassengeVo accompany:pass.getAccompanyingPassengerList()){
                    if(accompany.getPassageType().equals("2")){
                        chdCount++;
                    }else if(accompany.getPassageType().equals("3")){
                        infantCound++;
                    }
                }
            }
        }
        for(FlySegmentVo segment:flyOrderVo.getSegments()){//航段时间重新赋值(时区影响)
            for(Flights flight:flights){
                if(flight.getDepartureAirport().equals(segment.getDepCode())&&flight.getArrivalAirport().equals(segment.getArrCode())){
                    String departureDateD = flight.getDepartureDateD();
                    departureDateD=departureDateD.replace("T"," ");
                    Date dept =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(departureDateD);
                    String arrivalDateD = flight.getArrivalDateD();
                    arrivalDateD=arrivalDateD.replace("T"," ");
                    Date arr =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(arrivalDateD);
                    segment.setDepTime(dept);
                    segment.setArrTime(arr);
                }
            }
        }
        double total=0.0;
        for(TaxPrice tax:ticketPrice.get(0).getTaxPrices()) {
            total+=tax.getAmount()*(adtCount+chdCount+infantCound);
        }
        total+=totalFlyPrice.getAdultAmount()*adtCount;
        total+=totalFlyPrice.getChildrenAmount()*chdCount;
        total+=totalFlyPrice.getBabayAmount()*infantCound;
        modelAndView.addObject("adtCount", adtCount);
        modelAndView.addObject("chdCount",chdCount);
        modelAndView.addObject("infantCound",infantCound);
        String travlType=flyOrderVo.getSegments().get(0).getTravlType();
        String currency=flyOrderVo.getSegments().get(0).getCurrency();
        flyOrderVo.setTicketType(travlType);
        flyOrderVo.setCurrency(currency);
        flyOrderVo.setOrderCurrenry(currency);
        flyOrderVo.setTotalPrice(total);
        flyOrderVo.setOrderId(OrderNumberGenerator.getOrderNo()+"");
        Date createDate=new Date();
        flyOrderVo.setSetDate(createDate);
        flyOrderVo.setTimeLimit(new Date(createDate.getTime()+30*60*1000));
        TotalFlyPrice totalFlyPrice1 =(TotalFlyPrice)map.get("totalFlyPrice");

        List<TaxPrice> taxPrices =ticketPrice.get(0).getTaxPrices();


        String adultPassagesListStr = JSON.toJSONString(adultPassagesList);
        GlobalResult result=avService.addFlightOrder(flyOrderVo,totalFlyPrice1,taxPrices, UserUtils.getUserId(),"");
        if(result.getStatus()==200){
            Long id= (Long) result.getData();
            flyOrderVo.setId(id);
            modelAndView.addObject("flyOrderVo",flyOrderVo);
            modelAndView.setViewName("/en/Flyayment");
        }else {
            modelAndView.addObject("flyOrderVo",flyOrderVo);
            modelAndView.setViewName("/en/Flyayment");
        }
        return modelAndView;
    }

    /**
     * 判断客户端提交上来的令牌和服务器端生成的令牌是否一致
     *
     * @param request
     * @return true 用户重复提交了表单 false 用户没有重复提交表单
     */
    private boolean isRepeatSubmit(HttpServletRequest request) {
        String client_token = request.getParameter("tokenVal");
        // 1、如果用户提交的表单数据中没有token，则用户是重复提交了表单
        if (client_token == null) {
            return true;
        }
        // 取出存储在Session中的token
        String server_token = (String) request.getSession().getAttribute("token");
        // 2、如果当前用户的Session中不存在Token(令牌)，则用户是重复提交了表单
        if (server_token == null) {
            return true;
        }
        // 3、存储在Session中的Token(令牌)与表单提交的Token(令牌)不同，则用户是重复提交了表单
        if (!client_token.equals(server_token)) {
            return true;
        }

        return false;
    }

    @RequestMapping("/refundOrder")
    @ResponseBody
    public String refundOredr(@RequestBody String id){
        JsonData json = ticketService.ticketRefund(id);
        return json.getMsg();
    }

    @RequestMapping("/refundOrderN")
    @ResponseBody
    public String refundOredrN(@RequestBody String id){
        JsonData json = ticketService.refundTicket(id);
        return json.getMsg();
    }

    @RequestMapping("/refundAmount")
    @ResponseBody
    public String refundAmount(@RequestBody String id){
        JsonData json = ticketService.amountRefund(id);
        return json.getMsg();
    }


    @RequestMapping("/refundValid")
    @ResponseBody
    public String refundValid(@RequestBody String id){
        boolean b = ticketService.refundValid(id);
        return String.valueOf(b);
    }

    @RequestMapping("/refundClose")
    public void refundClose(@RequestBody String id){
        ticketService.refundClose(id);
    }

}
